package appfuse.framework.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.*;

public class HttpClientUtil {

    // 获得ConnectionManager，设置相关参数
    private static MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager();

    private static int connectionTimeOut = 60000;

    private static int socketTimeOut = 50000;

    private static int maxConnectionPerHost = 10;

    private static int maxTotalConnections = 50;

    // 标志初始化是否完成的flag
    private static boolean initialed = false;

    // 初始化ConnectionManger的方法
    private synchronized static void setPara() {
        manager.getParams().setConnectionTimeout(connectionTimeOut);
        manager.getParams().setSoTimeout(socketTimeOut);
        manager.getParams().setDefaultMaxConnectionsPerHost(
                maxConnectionPerHost);
        manager.getParams().setMaxTotalConnections(maxTotalConnections);
        initialed = true;
    }

    public static int getConnectionTimeOut() {
        return connectionTimeOut;
    }

    public static void setConnectionTimeOut(int connectionTimeOut) {
        HttpClientUtil.connectionTimeOut = connectionTimeOut;
    }

    public static int getSocketTimeOut() {
        return socketTimeOut;
    }

    public static void setSocketTimeOut(int socketTimeOut) {
        HttpClientUtil.socketTimeOut = socketTimeOut;
    }

    public static int getMaxConnectionPerHost() {
        return maxConnectionPerHost;
    }

    public static void setMaxConnectionPerHost(int maxConnectionPerHost) {
        HttpClientUtil.maxConnectionPerHost = maxConnectionPerHost;
    }

    public static int getMaxTotalConnections() {
        return maxTotalConnections;
    }

    public static void setMaxTotalConnections(int maxTotalConnections) {
        HttpClientUtil.maxTotalConnections = maxTotalConnections;
    }

    /**
     * Get方法获取url
     *
     * @param url
     * @param responseCharSet
     *
     * @return
     */
    public static String get(String url, String responseCharSet) {
        // 构造HttpClient的实例
        HttpClient client = new HttpClient(manager);

        if (!initialed) {
            HttpClientUtil.setPara();
        }
        // 创建GET方法的实例
        GetMethod get = new GetMethod(url);

        get.setFollowRedirects(true);

        String result = null;
        StringBuffer resultBuffer = new StringBuffer();

        try {

            client.executeMethod(get);

            // 在目标页面情况未知的条件下，不推荐使用getResponseBodyAsString()方法
            // String strGetResponseBody =
            // post.getResponseBodyAsString();
            BufferedReader in = new BufferedReader(new InputStreamReader(get
                    .getResponseBodyAsStream(), get.getResponseCharSet()));

            String inputLine = null;

            while ((inputLine = in.readLine()) != null) {
                resultBuffer.append(inputLine);
                //resultBuffer.append("\n");
            }

            in.close();

            result = resultBuffer.toString();

            // iso-8859-1 is the default reading encode
            result = HttpClientUtil.ConverterStringCode(
                    resultBuffer.toString(), get.getResponseCharSet(),
                    responseCharSet);
        } catch (Exception e) {
            e.printStackTrace();
            result = null;
        } finally {
            get.releaseConnection();
        }
        return result;
    }

    /**
     * Post方法获取url
     *
     * @param url
     * @param requestCharSet
     * @param responseCharSet
     *
     * @return
     */
    public static String post(String url, String requestCharSet,
                              String responseCharSet) {
    	return "";
    	/*
    	HttpClient client = new HttpClient(manager);

        if (!initialed) {
            HttpClientUtil.setPara();
        }        
        PostMethod post = new CharSetPostMethod(url, requestCharSet);
        post.setFollowRedirects(false);

        StringBuffer resultBuffer = new StringBuffer();

        String result = null;

        try {
            client.executeMethod(post);

            BufferedReader in = new BufferedReader(new InputStreamReader(post
                    .getResponseBodyAsStream(), post.getResponseCharSet()));
            String inputLine = null;

            while ((inputLine = in.readLine()) != null) {
                resultBuffer.append(inputLine);
                resultBuffer.append("\n");
            }

            in.close();

            // iso-8859-1 is the default reading encode
            result = HttpClientUtil.ConverterStringCode(
                    resultBuffer.toString(), post.getResponseCharSet(),
                    responseCharSet);
        } catch (Exception e) {
            e.printStackTrace();
            result = null;
        } finally {
            post.releaseConnection();
        }
        return result;
        */
    }

    /**
     * Post方法获取url
     *
     * @param url
     * @param requestCharSet
     * @param responseCharSet
     * @param nameValuePair
     *
     * @return
     */
    public static String post(String url, String requestCharSet,
                              String responseCharSet, NameValuePair[] nameValuePair) {
        HttpClient client = new HttpClient(manager);
        if (!initialed) {
            HttpClientUtil.setPara();
        }
        return "";
       /* PostMethod post = new CharSetPostMethod(url, requestCharSet);
        post.setRequestBody(nameValuePair);
        post.setFollowRedirects(false);
		
        String result = null;
        StringBuffer resultBuffer = new StringBuffer();

        try {
            client.executeMethod(post);
            BufferedReader in = new BufferedReader(new InputStreamReader(post
                    .getResponseBodyAsStream(), post.getResponseCharSet()));
            String inputLine = null;

            while ((inputLine = in.readLine()) != null) {
                resultBuffer.append(inputLine);
                resultBuffer.append("\n");
            }

            in.close();

            // iso-8859-1 is the default reading encode
            result = HttpClientUtil.ConverterStringCode(
                    resultBuffer.toString(), post.getResponseCharSet(),
                    responseCharSet);
        } catch (Exception e) {
            e.printStackTrace();
            result = null;
        } finally {
            post.releaseConnection();
        }
        return result;
        */
    }

    private static String ConverterStringCode(String source, String srcEncode,
                                              String destEncode) {
        if (source != null) {
            try {
                return new String(source.getBytes(srcEncode), destEncode);
            } catch (UnsupportedEncodingException e) {
                return "";
            }
        } else {
            return "";
        }
    }
}
